/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.century.sjt.EMChat.fragment;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.century.sjt.R;
import com.century.sjt.SjtHelper;
import com.century.sjt.SjtHelper.DataSyncListener;
import com.century.sjt.EMChat.activity.AddContactActivity;
import com.century.sjt.EMChat.activity.NewFriendsMsgActivity;
import com.century.sjt.activity.MainActivity;
import com.century.sjt.activity.MyActivity;
import com.century.sjt.activity.Topic.MyTopActivity;
import com.century.sjt.activity.ShopContacListActivity;
import com.century.sjt.EMChat.db.InviteMessgeDao;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;
import com.century.sjt.EMChat.widget.ContactItemView;
import com.century.sjt.widget.TitleBar.HomeTitleBar;
import com.easemob.chat.EMContactManager;
import com.century.sjt.EMChat.domain.EaseUser;
import com.easemob.util.EMLog;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.HashMap;
import java.util.Map;

/**
 * 联系人列表页
 * 
 */
public class ContactListFragment extends FragmentMail {
	
    private static final String TAG = ContactListFragment.class.getSimpleName();
    private ContactSyncListener contactSyncListener;
    private BlackListSyncListener blackListSyncListener;
    private ContactInfoSyncListener contactInfoSyncListener;
    private View loadingView;
    private ContactItemView applicationItem;
    private InviteMessgeDao inviteMessgeDao;
    private String isShop,isMerchant;
    @Override
    protected void initView() {
        super.initView();
        View headerView = LayoutInflater.from(getActivity()).inflate(R.layout.em_contacts_header, null);
        HeaderItemClickListener clickListener = new HeaderItemClickListener();
        applicationItem = (ContactItemView) headerView.findViewById(R.id.application_item);
        applicationItem.setOnClickListener(clickListener);
//        headerView.findViewById(R.id.group_item).setOnClickListener(clickListener);
//        headerView.findViewById(R.id.chat_room_item).setOnClickListener(clickListener);
//        headerView.findViewById(R.id.robot_item).setOnClickListener(clickListener);
        SharedPreferences mainSharedPreferences =getActivity(). getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
        isShop = mainSharedPreferences.getString("isShop", "");
        isMerchant = mainSharedPreferences.getString("isMerchant","");
//        if ("1".equals(isMerchant)||"1".equals(isShop)){
////            headerView.findViewById(R.id.group_item).setOnClickListener(clickListener);
////            headerView.findViewById(R.id.chat_room_item).setOnClickListener(clickListener);
////            headerView.findViewById(R.id.robot_item).setOnClickListener(clickListener);
//            headerView.findViewById(R.id.shop_item).setVisibility(View.GONE);
//            //添加headerview
//            listView.addHeaderView(headerView);
//        }else {
////            headerView.findViewById(R.id.group_item).setOnClickListener(clickListener);
////            headerView.findViewById(R.id.chat_room_item).setOnClickListener(clickListener);
////            headerView.findViewById(R.id.robot_item).setOnClickListener(clickListener);
//            headerView.findViewById(R.id.shop_item).setOnClickListener(clickListener);
//            //添加headerview
//            listView.addHeaderView(headerView);
//        }
        headerView.findViewById(R.id.shop_item).setOnClickListener(clickListener);
        //添加headerview
        listView.addHeaderView(headerView);
        //添加正在加载数据提示的loading view
        loadingView = LayoutInflater.from(getActivity()).inflate(R.layout.em_layout_loading_data, null);
        contentContainer.addView(loadingView);
        //注册上下文菜单
        registerForContextMenu(listView);

    }
    
    @Override
    public void refresh() {
        super.refresh();
        if(inviteMessgeDao == null){
            inviteMessgeDao = new InviteMessgeDao(getActivity());
        }
        if(inviteMessgeDao.getUnreadMessagesCount() > 0){
            applicationItem.showUnreadMsgView();
        }else{
            applicationItem.hideUnreadMsgView();
        }
    }

    @Override
    public void setOnRefresh() {
        SjtHelper.getInstance().setSyncingContactsWithServer(false);
        SjtHelper.getInstance().asyncFetchContactsFromServer(null);
    }


    @Override
    protected void setUpView() {
        titleBar = (HomeTitleBar) getView().findViewById(R.id.title_bar);
        titleBar.setTitle(getResources().getString(R.string.text_mail));
        titleBar.setRightIconResourc(getResources().getString(R.string.icon_plus));
        // 进入添加好友页
        titleBar.getRightLayout().setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                Intent intent = new Intent();
                intent.setClass(getActivity(), AddContactActivity.class);
                startActivity(intent);
            }
        });
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), MyActivity.class);
                startActivity(intent);
            }
        });
        //更新联系人数据
        //设置联系人数据
        setContactsMap(SjtHelper.getInstance().getContactList());
        super.setUpView();
        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String username = ((EaseUser)listView.getItemAtPosition(position)).getUsername();
                // demo中直接进入聊天页面，实际一般是进入用户详情页
                startActivity(new Intent(getActivity(), MyTopActivity.class).putExtra("username", username));
            }
        });

        



//        contactSyncListener = new ContactSyncListener();
//        SjtHelper.getInstance().addSyncContactListener(contactSyncListener);
//
//        blackListSyncListener = new BlackListSyncListener();
//        SjtHelper.getInstance().addSyncBlackListListener(blackListSyncListener);
//
//        contactInfoSyncListener = new ContactInfoSyncListener();
//        //添加到和环信第三方数据库
//        SjtHelper.getInstance().getUserProfileManager().addSyncContactInfoListener(contactInfoSyncListener);
        
        if (!SjtHelper.getInstance().isContactsSyncedWithServer()) {
            loadingView.setVisibility(View.VISIBLE);
        } else {
            loadingView.setVisibility(View.GONE);
        }
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
//        if (contactSyncListener != null) {
//            SjtHelper.getInstance().removeSyncContactListener(contactSyncListener);
//            contactSyncListener = null;
//        }
//
//        if(blackListSyncListener != null){
//            SjtHelper.getInstance().removeSyncBlackListListener(blackListSyncListener);
//        }
//
//        if(contactInfoSyncListener != null){
//           // 删除到环信第三方数据库
//            SjtHelper.getInstance().getUserProfileManager().removeSyncContactInfoListener(contactInfoSyncListener);
//        }

    }

    @Override
    public void onResume() {
        super.onResume();
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
        String image = sharedPreferences.getString("image", "");
        titleBar.setLeftImageResource(getActivity(),Constant.ImageHost_Big + image);
    }

    protected class HeaderItemClickListener implements OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.application_item:
                // 进入申请与通知页面
                startActivity(new Intent(getActivity(), NewFriendsMsgActivity.class));
                break;
//                 case R.id.group_item:
                // 进入群聊列表页面
//                startActivity(new Intent(getActivity(), GroupsActivity.class));
//                break;
//                case R.id.chat_room_item:
                //进入聊天室列表页面
//                startActivity(new Intent(getActivity(), PublicChatRoomsActivity.class));
//                break;
//                case R.id.robot_item:
                //进入Robot列表页面
//                startActivity(new Intent(getActivity(), RobotsActivity.class));
//                break;
                case R.id.shop_item:
                //进入商家列表、
                startActivity(new Intent(getActivity(), ShopContacListActivity.class));
                break;
            default:
                break;
            }
        }
	    
	}
	

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
	    toBeProcessUser = (EaseUser) listView.getItemAtPosition(((AdapterContextMenuInfo) menuInfo).position);
	    toBeProcessUsername = toBeProcessUser.getUsername();

        if (!toBeProcessUsername.equals("00000000")){
            getActivity().getMenuInflater().inflate(R.menu.em_context_contact_list, menu);
        }else {

        }
        getActivity().getMenuInflater().inflate(R.menu.em_context_contact_list, menu);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.delete_contact) {
            if ("00000000".equals(toBeProcessUsername)){
                return true;
            }
			try {
                // 删除此联系人
                deleteContact(toBeProcessUser);
            } catch (Exception e) {
                e.printStackTrace();
            }
			return true;
		}
//        else if(item.getItemId() == R.id.add_to_blacklist){
//			moveToBlacklist(toBeProcessUsername);
//			return true;
//		}
		return super.onContextItemSelected(item);
	}


	/**
	 * 删除联系人
	 * 
	 * @param toDeleteUser
	 */
	public void deleteContact(final EaseUser tobeDeleteUser) {

        sjtDeleteContact(tobeDeleteUser);//sjt删除好友接口


	}

    private void sjtDeleteContact(final EaseUser tobeDeleteUser) {

        //显示Progress Dialog
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getActivity().getResources().getString(R.string.error_please_waitting), getActivity());
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.DeleteFriend, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.log("删除联系人接口成功返回"+tobeDeleteUser.getUsername().toString(), response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        TipUtil.closeProgressDialog();
                        // 删除相关的邀请消息
                        InviteMessgeDao dao = new InviteMessgeDao(getActivity());
                        dao.deleteMessage(toBeProcessUser.getUsername());
                        emDeleteContact(tobeDeleteUser);//换新更新联系人

                    }else if (code.equals("501")) {//服务器找不到好友
                        TipUtil.closeProgressDialog();
                        emDeleteContact(tobeDeleteUser);//换新更新联系人

                    } else {//失败
                        TipUtil.showToast(message, getActivity(), 1);
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getActivity().getResources().getString(R.string.error_service), getActivity(), 1);
                }
                TipUtil.closeProgressDialog();

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getActivity().getResources().getString(R.string.error_network), getActivity(), 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = getActivity().getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                String mobile = mainSharedPreferences.getString("mobile", "");
                map.put("loginId", userId);
                map.put("userId",userId);
                map.put("friendId", tobeDeleteUser.getUsername());
//                map.put("mobile", mobile);
                return map;

            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getActivity().getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
//                Log.e("cookie", cookieValue);
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        MainActivity act = (MainActivity)getActivity();
        act.getQueue().add(stringRequest);
//        mQueue.add(stringRequest);
    }

    private void emDeleteContact(final EaseUser tobeDeleteUser) {
        String st1 = getResources().getString(R.string.deleting);
        final String st2 = getResources().getString(R.string.Delete_failed);
        final ProgressDialog pd = new ProgressDialog(getActivity());
        pd.setMessage(st1);
        pd.setCanceledOnTouchOutside(false);
        pd.show();

        new Thread(new Runnable() {
            public void run() {
                try {
                    //删除好友

//                    EMContactManager.getInstance().deleteContact(tobeDeleteUser.getUsername());
                    // 删除db和内存中此用户的数据
                    SjtHelper.getInstance().getContactList().remove(tobeDeleteUser.getUsername());
                    getActivity().runOnUiThread(new Runnable() {
                        public void run() {
                            pd.dismiss();
                            contactList.remove(tobeDeleteUser);
                            contactListLayout.refresh();
                        }
                    });
                } catch (final Exception e) {
                    getActivity().runOnUiThread(new Runnable() {
                        public void run() {
                            pd.dismiss();
                            Toast.makeText(getActivity(), st2 + e.getMessage(), 1).show();
                        }
                    });

                }

            }
        }).start();
    }
    class ContactSyncListener implements DataSyncListener {
        @Override
        public void onSyncComplete(final boolean success) {
            EMLog.d(TAG, "on contact list sync success:" + success);
            getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    getActivity().runOnUiThread(new Runnable(){

                        @Override
                        public void run() {
                            if(success){
                                loadingView.setVisibility(View.GONE);
                                refresh();
                            }else{
                                String s1 = getResources().getString(R.string.get_failed_please_check);
                                Toast.makeText(getActivity(), s1, 1).show();
                                loadingView.setVisibility(View.GONE);
                            }
                        }

                    });
                }
            });
        }
    }
    
    class BlackListSyncListener implements DataSyncListener {

        @Override
        public void onSyncComplete(boolean success) {
            getActivity().runOnUiThread(new Runnable(){

                @Override
                public void run() {
                    blackList = EMContactManager.getInstance().getBlackListUsernames();
                    refresh();
                }
                
            });
        }
        
    };
    
    class ContactInfoSyncListener implements DataSyncListener {

        @Override
        public void onSyncComplete(final boolean success) {
            EMLog.d(TAG, "on contactinfo list sync success:" + success);
            getActivity().runOnUiThread(new Runnable() {
                
                @Override
                public void run() {
                    loadingView.setVisibility(View.GONE);
                    if(success){
                        refresh();
                    }
                }
            });
        }
        
    }
	
}
